//
//  TKIMLocationViewController.m
//  TKIM
//
//  Created by liupm on 15/10/27.
//  Copyright © 2015年 liupm. All rights reserved.
//

#import "TKIMLocationViewController.h"
//#import "TKIMLocationHelper.h"
#import "TKIMLayerUtils.h"
//#import "TKIMImageHelper.h"

@interface TKIMLocationViewController ()<TKIMLocationDelegate>
@property(nonatomic,strong) TKIMLocationHelper *locationHelper;
@property(nonatomic,strong) MKMapView *mapView;
@property(nonatomic,strong) TKIMLayerUtils  *layerUtils;
@end

@implementation TKIMLocationViewController




-(void)loadView
{
    [super loadView];
    self.navigationItem.title = @"位置信息";
    
    _layerUtils = [[TKIMLayerUtils alloc] initWithContent:self.view];
    
    _locationHelper = [[TKIMLocationHelper alloc] init];
    _locationHelper.delegate = self;
    
    self.mapView =[_locationHelper getMapView:self.view.frame];
    [self.view addSubview:self.mapView];
    
    //定位
    if (!_location)
    {
        self.navigationItem.rightBarButtonItem  = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStyleBordered target:self action:@selector(sendLocation)];
        [_layerUtils showLoading:YES withLabel:@"正在定位"];
        [_locationHelper startLocation];
    }
    //加标注
    else
    {
        [_locationHelper addAnnotation:_location.latitude longitude:_location.longitude title:_location.address];
    }
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_layerUtils showLoading:NO];
}


/**
 *  @Author lpm, 15-10-27 13:10:50
 *
 *  @brief  发送定位信息
 */
-(void)sendLocation
{
    if (_location)
    {
        if (_delegate && [_delegate respondsToSelector:@selector(sendLocation:)])
        {
            CGRect rect = CGRectMake(0, self.mapView.frame.size.height*0.2, self.mapView.frame.size.width, self.mapView.frame.size.height*0.4);
            UIImage *img = [TKIMImageHelper screenshotWithRect:rect view:self.mapView];
            _location.addressImage = img;
            [_delegate sendLocation:_location];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else
    {
        [[TKIMLayerUtils instance] showTip:@"暂时无法获取位置信息"];
    }
}


/**
 *  @Author lpm, 15-10-27 13:10:44
 *
 *  @brief  定位到用户的地理位置
 *
 *  @param userLocation
 */
-(void)didReceiveUserLocation:(NSMutableDictionary *)userLocation
{
    [_layerUtils showLoading:NO];
    _location = [[TKIMLocationMessage alloc] init];
    _location.address = userLocation[@"address"];
    _location.latitude = [userLocation[@"latitude"] floatValue];
    _location.longitude = [userLocation[@"longitude"] floatValue];
}


/**
 *  @Author lpm, 15-10-27 13:10:54
 *
 *  @brief  定位用户地理位置失败
 *
 *  @param error
 */
-(void)didFailToLocateUserWithError:(NSString *)errorInfo
{
    [_layerUtils showLoading:NO];
    [_layerUtils showTip:errorInfo];
}

@end
